import { reactive, toRefs, ref } from 'vue'
import { defineStore } from 'pinia'
import type { Tag } from '@/typings'
import { homeMenuPath } from '@/stores/menu'

export const useTagStore = defineStore('tag', () => {
  const state = reactive({
    visitedTags: [] as Tag[]
  })
  const currentTag = ref({} as Tag)

  const addVisitedTag = (tag: Tag) => {
    if (!state.visitedTags.some((t: Tag) => t.path === tag.path)) {
      // 不重复添加
      state.visitedTags.push(
        Object.assign({}, tag, {
          title: tag.meta.title || 'no-name'
        })
      )
    }
  }

  const delVisitedTag = (tag: Tag) => {
    for (const [i, v] of state.visitedTags.entries()) {
      if (v.path === tag.path) {
        state.visitedTags.splice(i, 1)
        break
      }
    }
  }

  const delOtherVisitedTags = (tag: Tag) => {
    state.visitedTags = state.visitedTags.filter((t: Tag) => {
      // 固定的菜单和当前菜单不删除，其他都删除
      return t.meta.affix || t.path === tag.path
    })
  }

  const delAllVisitedTags = () => {
    // keep affix tags
    const affixTags = state.visitedTags.filter((tag: Tag) => tag.meta.affix)
    state.visitedTags = affixTags
  }

  const updateVisitedTag = (tag: Tag) => {
    for (let v of state.visitedTags) {
      if (v.path === tag.path) {
        v = Object.assign(v, tag)
        break
      }
    }
  }

  const addTag = (tag: Tag) => {
    addVisitedTag(tag)
    currentTag.value = tag
  }

  const delTag = (tag: Tag) => {
    delVisitedTag(tag)
  }

  const delOtherTags = (tag: Tag) => {
    delOtherVisitedTags(tag)
  }

  const delAllTags = () => {
    delAllVisitedTags()
  }

  const closeCurrent = (router: any) => {
    //关闭当前页面
    const id = currentTag.value.id
    const fullPath = currentTag.value.fullPath
    delTag(currentTag.value)
    const latestTag = state.visitedTags.slice(-1)[0]
    if (latestTag) {
      router.push(latestTag.fullPath)
    } else {
      // now the default is to redirect to the home page if there is no tags-view,
      // you can adjust it according to your needs.
      if (id === homeMenuPath) {
        // to reload home page
        router.replace({ path: '/redirect' + fullPath })
      } else {
        // 只有 选在非首页的时候，关闭“所有”, 并且没有affix菜单的情况下 才会执行到这个, 这种情况的架构几乎不存在
        router.push('/')
      }
    }
  }

  return { ...toRefs(state), addTag, delTag, addVisitedTag, delOtherTags, delAllTags, updateVisitedTag, closeCurrent }
})
